package sisi.payment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.ListaStandardWindow;


/**
 * PaymentsWindow.java - Controller class for <i>Payments terms window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 18/11/2013
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class PaymentsWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose, ListaStandardWindow {
	
	// listbox boxPaymentsmode
	private Window windowPayments, windowEditPayment;
	private Textbox tbCerca;
	private Listbox boxPayments;

	private List tutti_i_payments;
	private boolean lNuovo;
	private Toolbarbutton buttonSeleziona;

	private ListModelList listModelList;
	private Integer idSelezionato = 0;

	protected Map<String, Object> args;
	private Object paymentItem;
	private Payment modPayment;
	// edit
	private Intbox id, dd;
	private Textbox terms;

	public void onCreate$windowPayments(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N"
				: tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		tutti_i_payments = new PaymentsController().getPaymentList(null);
		listModelList.addAll(tutti_i_payments);
		boxPayments.setModel(listModelList);
		boxPayments.setItemRenderer(new PaymentsItemRenderer());
		
		if (idSelezionato!=null && idSelezionato!=0){
			for (int i = 0; i < tutti_i_payments.size(); i++) {
				Payment payment = (Payment)tutti_i_payments.get(i);
				if (payment.getId()==idSelezionato.intValue()){
					boxPayments.setSelectedIndex(i);
					break;
				}
			}
		}

	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}
	
	public void onClick$buttonCerca(Event event) {
		cerca();
	}
	
	
	private void cerca(){
		listModelList = new ListModelList();
		tutti_i_payments = new PaymentsController().getPaymentList(tbCerca
				.getValue());
		listModelList.addAll(tutti_i_payments);
		boxPayments.setModel(listModelList);
		boxPayments.setItemRenderer(new PaymentsItemRenderer());		
	}
	
	
	
	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}
	
	
	public void onClick$buttonSeleziona(Event event) {

		seleziona();

	}

	public void seleziona() {
		if (boxPayments.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oPayment = boxPayments.getSelectedItem().getAttribute(
					"rigaPayment");
			String codiceSelezionato = ""+((Payment) oPayment).getId();
			Sessions.getCurrent().setAttribute("codicePaymentSelezionato",
					codiceSelezionato);
			windowPayments.detach();
		}
	}


	@Override
	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	@Override
	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}
	
	private void modifica(boolean nuovo){
		try {

			int nIndex = boxPayments.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a Payment Terms to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxPayments", boxPayments);
				Window finestraEditPayment = (Window) Executions.createComponents(
						"/editPayment.zul", null, map);
				finestraEditPayment.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void onClick$buttonCancella(Event event) {
		// TODO Auto-generated method stub
		
	}	

	public class PaymentsItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Payment) data).getId()).setParent(li);
			new Listcell(((Payment) data).getTerms()).setParent(li);
			new Listcell(""+((Payment) data).getDd()).setParent(li);
			li.setAttribute("rigaPayment", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}

	
	
	// EDIT PAYMENT TERM: NEW/MODIFY
	public void onCreate$windowEditPayment(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		boxPayments = (Listbox) args.get("boxPayments");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		if (!lNuovo) {
			paymentItem = boxPayments.getSelectedItem().getAttribute("rigaPayment");
			modPayment = new PaymentsController().refreshPayment((Payment) paymentItem);
			paymentItem = modPayment;
			windowEditPayment.setTitle("Edit Payment Terms");
			terms.setFocus(true);
			id.setValue(modPayment.getId());
			terms.setValue(modPayment.getTerms());
			dd.setValue(modPayment.getDd());
		} else {
			windowEditPayment.setTitle("New Payment Terms");
			terms.setFocus(true);
		}
	}
	
	public void onClick$btnAnnulla(Event event){
		windowEditPayment.detach();
	}
	
	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modPayment = new Payment();
		} else {

		}
		String testoMsg = "";
		
		modPayment.setId(id.getValue());
		modPayment.setTerms(General.toUpperAncheNull(terms.getValue()));
		modPayment.setDd( (dd.getValue()!=null?dd.getValue():0));
		
		if (lNuovo){
			new PaymentsController().addPayment(modPayment);
			testoMsg = "Adding Payment Terms: "+ General.trimNull( modPayment.getTerms() );
		} else {
			new PaymentsController().updatePayment(modPayment);
			testoMsg = "Updating Payment Terms: "+ General.trimNull( modPayment.getTerms() );			
		}
		
		General.showNotify( testoMsg, windowEditPayment);
		
		windowEditPayment.detach();
		
		// aggiorna listbox
		
		if (lNuovo){
			ListModelList lml = (ListModelList) boxPayments.getListModel();
			lml.add(modPayment);
			boxPayments.setSelectedIndex(lml.indexOf(modPayment));
		} else {
			ListModelList lml = (ListModelList) boxPayments.getListModel();
			Object oPaymentItem = boxPayments.getSelectedItem().getAttribute("rigaPayment");
			if (lml.indexOf(oPaymentItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oPaymentItem), modPayment);
			}
		}		
	}
	
	
}
